<template>
    <div>
        <el-row>
            <el-col :span="17" :offset="1">
                <div>
                    <h2>{{ currentNews.title }}</h2>
                    <time>{{ moment(currentNews.editTime).format("lll") }}</time>
                    <el-divider></el-divider>
                    <div v-html="currentNews.content"></div>
                </div>
            </el-col>

            <el-col :span="5" :offset="1">
                <el-card style="max-width: 480px">
                    <template #header>
                        <div class="card-header">
                            <span style="font-size: 16px;font-weight: bold;">最近新闻</span>
                        </div>
                    </template>
                    <div v-for="item in topNews" :key="item._id" style="padding: 14px;" @click="handleChange(item._id)">
                        <span>{{ item.title }}</span>
                        <div class="bottom">
                            <time>{{  moment(item.editTime).format("lll") }}</time>
                        </div>
                    </div>
                </el-card>
            </el-col>
        </el-row>
    </div>
</template>

<script setup>
import axios from 'axios';
import moment from 'moment';
import { ref ,watchEffect,onBeforeUnmount} from 'vue';
import { useRoute,useRouter } from 'vue-router';

moment.locale("zh-cn")
const currentNews = ref({})
const topNews = ref([])
const route = useRoute()
const router = useRouter()
const watch = watchEffect(async () => {

    if(!route.params.id) return 
    const res = await axios.get(`/webapi/news/list/${route.params.id}`)
    const toplist = await axios.get(`/webapi/news/toplist?limit=4`)
    currentNews.value = res.data.data[0]
    topNews.value = toplist.data.data
})
 
onBeforeUnmount(()=>{
    watch()
})

const handleChange = (id)=>[
    router.push(`/news/${id}`)
]
</script>
<style lang="scss" scoped>
.el-row {
    margin-top: 30px;
}

time {
    font-size: 13px;
    color: gray;
}
</style>